<template>
    <div class="marketing_coupon">
        <!-- 新增操作 -->
        <div class="marketing_coupon_top">
            <el-row class="marketing_coupon_header" :gutter="10">
                <el-col v-for="{ typeName, type, typeDesc } in groupTypeList" :key="type" :span="8">
                    <div class="marketing_coupon_header_item">
                        <div>
                            <h3>
                                {{ typeName }}
                            </h3>
                            <p v-html="typeDesc"></p>
                        </div>
                        <el-button type="primary" @click="routerHandler(type)" v-auth="'coupon_list:create'"
                            >立即新增</el-button
                        >
                    </div>
                </el-col>
            </el-row>
        </div>
        <div class="marketing_coupon_bottom">
            <!-- 查询 -->
            <div class="zw-form-layout">
                <el-form ref="formRef" :model="form" label-width="auto">
                    <el-row :gutter="24">
                        <el-col :span="8">
                            <el-form-item label="优惠券名称/标题" prop="couponName">
                                <el-input
                                    v-model="form.couponName"
                                    clearable
                                    placeholder="请输入优惠券名称/标题"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="类型" prop="couponType">
                                <el-select v-model="form.couponType" placeholder="全部类型">
                                    <el-option
                                        v-for="item in couponTypeList"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="5">
                            <el-form-item label="状态" prop="couponStatus">
                                <el-select v-model="form.couponStatus" placeholder="全部状态">
                                    <el-option
                                        v-for="item in couponStatusListCopy"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6" class="zw-form-btns">
                            <el-button type="primary" @click="searchHandler" v-auth="'coupon_list:query'"
                                >查询</el-button
                            >
                            <el-button plain @click="resetHandler">清空</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <!-- 列表 -->
            <el-table :data="tableList" :stripe="true">
                <el-table-column v-for="{ prop, ...rest } in tableColumns" :key="prop" :prop="prop" v-bind="rest">
                    <template v-if="['couponName', 'operations', 'couponStatusText'].includes(prop)" #default="{ row }">
                        <template v-if="prop === 'couponName'">
                            <!-- <el-link type="primary" class="custom-el-link" @click="nameRouteHandler(row, 'group')">{{
                                row.couponName
                            }}</el-link> -->
                            <div class="custom-el-link">
                                <span @click="nameRouteHandler(row, 'group')">{{ row.couponName }}</span>
                            </div>
                        </template>
                        <template v-if="prop === 'couponStatusText'">
                            <span :class="`custom-status-${row.couponStatus}`">{{ row.couponStatusText }}</span>
                        </template>
                        <template v-if="prop === 'operations'">
                            <el-button
                                v-for="{ label, fn, ref, auth } in row.operations"
                                :key="label"
                                @click="fn(row, ref)"
                                size="small"
                                :ref="el => setItemRef(el, `${ref}${row.id}`)"
                                class="table-button"
                                v-auth="auth"
                                >{{ label }}</el-button
                            >
                        </template>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div style="margin-top: 15px">
                <Pagination
                    :total="totalCount"
                    :page-size="form.perPage"
                    :current-page="form.page"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
        </div>
        <!-- popover弹窗 -->
        <el-popover
            popper-class="custom-coupon-popover-class not-close"
            ref="popoverRef"
            :virtual-ref="buttonRef"
            placement="top"
            trigger="click"
            virtual-triggering
            :width="currentRow.ref === 'spreadButtonRef' ? 400 : 240"
            :visible="popoverVisible">
            <div
                class="custom-coupon-popover-class-main"
                v-click-outside="onClickOutside"
                v-if="['disableButtonRef', 'removeButtonRef', 'enableButtonRef'].includes(currentRow.ref)">
                <!-- 启用、失效、删除 -->
                <h3 style="margin-bottom: 16px">
                    <el-icon class="custom-icon"><WarningFilled /></el-icon>
                    <!-- 删除 -->
                    <template v-if="currentRow.ref == 'removeButtonRef'"> 确定要删除该优惠券吗？ </template>
                    <!-- 启用 -->
                    <template v-if="currentRow.ref == 'enableButtonRef'"
                        >优惠券启用后将可以领取，确定要启用该优惠券吗？</template
                    >
                    <!-- 失效 -->
                    <template v-if="currentRow.ref == 'disableButtonRef'">
                        优惠券失效后将无法领取，已领取的优惠券不受影响，确定要失效该优惠券吗？
                    </template>
                </h3>
                <div style="text-align: right">
                    <el-button size="small" @click="popoverVisibleHandler()">取消</el-button>
                    <el-button size="small" type="primary" @click="popoverConfirmHandler()">确定</el-button>
                </div>
            </div>
            <SpreadBox
                v-if="popoverVisible && currentRow.ref === 'spreadButtonRef'"
                :path="path"
                :params="params"
                :downloadName="downloadName"
                :popoverFn="popoverVisibleHandler" />
        </el-popover>
    </div>
</template>

<script setup name="marketingCoupon">
import { ref, unref, reactive, computed, onMounted, onUnmounted, onActivated, onDeactivated, nextTick } from 'vue';
import { onBeforeRouteLeave, useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { ClickOutside as vClickOutside } from 'element-plus';
import request from '@/request/index';
import constants from '@/commons/constants';
import { packSelectObjUtil, downloadImgHandler, floatDivide } from '@/commons/utils';
import { setLayout, resetLayout } from '@/hooks/layout';
import Pagination from '@/components/Pagination.vue';
import SpreadBox from '@/components/SpreadBox.vue';
import { cloneDeep } from '../../../../commons/utils';
import store from '@/store/index';
import { useDocumentVisibility } from '@/hooks/dom';
import storage from '@/commons/storage';

const router = useRouter();
const couponStatusList = reactive(packSelectObjUtil(constants.COUPON_STATUS_OPTIONS));
const couponTypeList = reactive(packSelectObjUtil(constants.COUPON_TYPE_OPTIONS));
const couponStatusListCopy = [
    couponStatusList[0],
    couponStatusList[3],
    couponStatusList[4],
    couponStatusList[1],
    couponStatusList[2]
];

// 顶部新增和Tabs Dom
let groupTypeList = reactive([
    { typeName: '满减券', typeDesc: '满减券可为用户抵扣商品金额<br>例如：满100元减20元。', type: 1 },
    { typeName: '折扣券', typeDesc: '折扣券可为用户进行商品打折<br>例如：满100元打9折。', type: 2 }
]);
const form = reactive({
    page: 1, //分页页码，数字类型
    perPage: 10, //默认每页15条
    couponName: '', //优惠券
    couponStatus: 0,
    couponType: 0
});
let formClone = cloneDeep(form);
const formRef = ref(null);
const totalCount = ref(0);
let tableList = reactive([]);

// popover ref
let popoverVisible = ref(false);
const itemRefs = {};
const setItemRef = (el, key) => {
    if (el) {
        itemRefs[key] = el;
    }
};
const popoverRef = ref(null);
const buttonRef = ref(null);
let currentRow = reactive({ ref: null });

const tableColumns = computed(() => {
    const baseTableColumns = [
        { label: '优惠券名称', prop: 'couponName', showOverflowTooltip: true, minWidth: '180' },
        { label: '优惠券标题', prop: 'couponTitle', showOverflowTooltip: true, minWidth: '150' },
        { label: '类型', prop: 'couponTypeText', width: '80' },
        { label: '优惠内容', prop: 'couponDiscountContentText', showOverflowTooltip: true, minWidth: '120' },
        { label: '状态', prop: 'couponStatusText', width: '90' },
        { label: '已领取', prop: 'couponAcquiredNumber', width: '100', sortable: true },
        { label: '已使用', prop: 'couponUsedNumber', width: '100', sortable: true },
        { label: '剩余', prop: 'resetNumber', width: '100', sortable: true },
        { label: '支付金额（元）', prop: 'couponPaidNumberText', width: '150' },
        { label: '笔单价（元）', prop: 'couponPerCustomerPriceText', width: '150' },
        { label: '操作', prop: 'operations', width: '210', fixed: 'right' }
    ];
    return baseTableColumns;
});

const nameRouteHandler = ({ id }, type) => {
    const useAuth = store.useAuthStore();
    const permissions = useAuth.permissions;
    const code = 'coupon_list:query';
    if (!permissions.has(code)) {
        ElMessage({
            type: 'error',
            message: '当前用户没有查看权限'
        });
        return false;
    }
    const { href } = router.resolve({
        path: '/marketing/coupon/detail',
        query: {
            id,
            type
        }
    });
    window.open(href, '_blank');
};
const routerHandler = type => {
    const paths = {
        1: '/marketing/coupon/enoughAdd',
        2: '/marketing/coupon/discountAdd'
    };
    router.push({ path: paths[type] });
};
// 以下有时间抽离成公共查询js
/**
 * 分页
 * @param {*} page
 */
const changePageHandler = page => {
    form.page = page;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} perPage
 */
const changeSizeHandler = perPage => {
    form.page = 1;
    form.perPage = perPage;
    queryCouponListHandler();
};

const couponContent = row => {
    const obj = (row?.couponInfo || [])[0] || {};
    let pre = '';
    let num = '';
    switch (obj.couponPrerequisites) {
        case 1:
            pre = '无门槛';
            break;
        case 2:
            pre = `满${floatDivide(obj.couponPrerequisitesAdditional, 100)}`;
            break;
        case 3:
            pre = `满${obj.couponPrerequisitesAdditional}件`;
            break;
        default:
            break;
    }
    switch (obj.couponType) {
        case 1:
            num = `减${floatDivide(obj.couponDiscountContent, 100)}`;
            break;
        case 2:
            num = `打${floatDivide(obj.couponDiscountContent, 100)}折`;
            break;
        default:
            break;
    }
    return pre + num;
};
/**
 * 分页查询
 */
const queryCouponListHandler = async () => {
    const _form = cloneDeep(form);
    _form.couponStatus = _form.couponStatus || null;
    _form.couponType = _form.couponType || null;
    const res = await request('couponListServ', _form);
    const list = (res.data.list || []).map(item => {
        item.couponTypeText = item.couponType === 1 ? '满减券' : '折扣券';
        item.couponDiscountContentText = couponContent(item) || '-';
        const { couponStatus, couponStatusName, couponTotal, couponTitle } = (item.couponInfo || [])?.[0] || {};
        item.couponStatus = couponStatus;
        item.couponStatusText = couponStatusName || '-';
        item.couponTitle = couponTitle || '-';
        item.resetNumber = couponTotal ? couponTotal - item.couponAcquiredNumber : '-';
        item.couponPaidNumberText = floatDivide(item.couponPaidNumber, 100);
        // todo:笔单价，现在的是客单价
        item.couponPerCustomerPriceText = floatDivide(item.couponPerCustomerPrice, 100);
        // 根据不同状态显示不同按钮
        // 3已失效 4已过期 5未启用 6已启用
        const btns = [
            // { label: '详情', fn: routerHandler, ref: 'infoButtonRef', auth: 'coupon_list:query' },
            { label: '编辑', fn: editHandler, ref: 'editButtonRef', auth: 'coupon_list:edit' },
            { label: '推广', fn: spreadHandler, ref: 'spreadButtonRef', auth: 'coupon_list:spread' },
            { label: '启用', fn: enableHandler, ref: 'enableButtonRef', auth: 'coupon_list:enable' },
            { label: '失效', fn: disableHandler, ref: 'disableButtonRef', auth: 'coupon_list:invalid' },
            { label: '删除', fn: removeHandler, ref: 'removeButtonRef', auth: 'coupon_list:remove' }
        ];
        item.operations = [];
        if (couponStatus == 5) {
            item.operations.push(btns[0], btns[2], btns[4]);
        } else if (couponStatus == 6) {
            item.operations.push(btns[0], btns[1], btns[3]);
        } else if ([3, 4].includes(couponStatus / 1)) {
            item.operations.push(btns[4]);
        }
        return item;
    });
    tableList.length = 0;
    tableList.push(...list);
    totalCount.value = res.data.totalCount;
};
/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    searchHandler();
    formClone = cloneDeep(form);
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.page = 1;
    formClone = cloneDeep(form);
    queryCouponListHandler();
};
/** 按钮组操作 */
const popoverHandler = (row, ref) => {
    Object.assign(currentRow, row);
    currentRow.ref = ref;
    buttonRef.value = itemRefs[`${ref}${row.id}`];

    nextTick(() => {
        popoverVisibleHandler(true);
    });
};
// 编辑
const editHandler = row => {
    const editType = {
        1: 'enoughEdit',
        2: 'discountEdit'
    };
    router.push({
        path: `/marketing/coupon/${editType[row.couponType]}`,
        query: {
            id: row.id
        }
    });
};
// 推广
let path = ref();
let params = ref();
let downloadName = ref();
const spreadHandler = async (row, ref) => {
    path.value = 'pages-user/coupon/receive';
    params.value = `couponId=${row.couponId}&shopId=${storage.get('ZW-SHOPID')}`;
    downloadName.value = row.couponName;
    popoverHandler(row, ref);
};
// 启用
const enableHandler = (row, ref) => {
    popoverHandler(row, ref);
};
// 失效
const disableHandler = (row, ref) => {
    popoverHandler(row, ref);
};
// 删除
const removeHandler = (row, ref) => {
    popoverHandler(row, ref);
};

// 点击popover外部
const onClickOutside = el => {
    popoverVisibleHandler();
};
// 控制popover展示隐藏
const popoverVisibleHandler = (visible = false) => {
    popoverVisible.value = visible;
};
// popover确定
const popoverConfirmHandler = async () => {
    let method = null;
    let params = null;
    if (currentRow.ref == 'disableButtonRef') {
        // 失效
        method = 'couponExpireServ';
        params = { id: currentRow.id, couponStatus: 3 };
    } else if (currentRow.ref == 'enableButtonRef') {
        // 启用
        method = 'couponEnable';
        params = { id: currentRow.id };
    } else if (currentRow.ref == 'removeButtonRef') {
        // 删除
        method = 'couponDestroy';
        params = { id: [currentRow.id] };
    }

    await request(method, params);
    popoverVisibleHandler();
    queryCouponListHandler();
    ElMessage({
        type: 'success',
        message: '操作成功'
    });
};

//切换tab筛选
const tabHandler = () => {
    searchHandler();
};

const visibilitychange = () => {
    // 页面可见
    if (document.visibilityState === 'visible') {
        queryCouponListHandler();
    }
};

const getAllData = () => {
    queryCouponListHandler();
};

onActivated(() => {
    // Object.keys(formClone || {})?.forEach(key => {
    //     form[key] = formClone[key];
    // });
    getAllData();
    setLayout();
    useDocumentVisibility('add', visibilitychange);
});
onDeactivated(() => {
    resetLayout();
    useDocumentVisibility('remove', visibilitychange);
});

onBeforeRouteLeave((to, from, next) => {
    if (!/\/marketing\/coupon/.test(to?.path)) {
        Object.keys(formClone || {})?.forEach(key => {
            form[key] = formClone[key];
        });
    }
    next();
});
</script>
<style lang="scss">
.custom-coupon-popover-class {
    padding: 0px !important;
    &-main {
        padding: 16px !important;
    }
    h3,
    p {
        margin: 0;
    }
    h3 {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
        display: flex;
        align-items: flex-start;
        margin-bottom: 10px;
        .custom-icon {
            width: 14px;
            height: 14px;
            margin-right: 9px;
            color: #faad14;
            margin-top: 2px;
        }
    }

    p {
        padding-left: 23px;
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #969696;
        line-height: 16px;
        margin: 0 0 16px;
    }

    p + div {
        text-align: right;
    }
}
</style>
<style lang="scss" scoped>
@import './scss/index.scss';
</style>
